import { ChangeDetectorRef, Component, OnInit } from '@angular/core';
import { _HttpClient } from '@delon/theme';
import * as moment from 'moment';
import { NzSafeAny } from 'ng-zorro-antd/core/types';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalRef } from 'ng-zorro-antd/modal';
import { zip } from 'rxjs';
import { finalize } from 'rxjs/operators';

@Component({
  selector: 'app-business-order-on-purchase',
  templateUrl: './on-purchase.component.html'
})
export class BusinessOrderOnPurchaseComponent implements OnInit {
  i: any;
  itemCurrent: any;
  purchase: any;
  purchase_types: any;

  constructor(private modal: NzModalRef, private msgSrv: NzMessageService, private http: _HttpClient, private cdr: ChangeDetectorRef) {}

  ngOnInit(): void {
    if (this.i.orderSn != '') {
      this.loadDataFromServer(this.i.shopId, this.i.orderSn, this.i.itemId, this.i.skuId);
    }
  }

  loadDataFromServer(shopId: number, orderSn: string, itemId: string, skuId: string) {
    zip(
      this.http.get(`api/order/item_current`, { shopId: shopId, orderSn: orderSn }),
      this.http.get(`api/purchases`, { shopId: shopId, orderSn: orderSn, itemId: itemId, skuId: skuId })
    )
      .pipe(
        finalize(() => {
          this.cdr.detectChanges();
        })
      )
      .subscribe(([itemCurrent, purchases]: [NzSafeAny, NzSafeAny]) => {
        // this.i = true;
        console.log(purchases);
        this.itemCurrent = itemCurrent.data;
        this.purchase = purchases?.data;
      });
  }

  reload(): void {
    this.cdr.detectChanges();
    this.http
      .get(`api/purchases`, { shopId: this.i.shopId, orderSn: this.i.orderSn, itemId: this.i.itemId, skuId: this.i.skuId })
      .subscribe(res => {
        this.cdr.detectChanges();
        this.purchase = res?.data;
      });
  }

  close(): void {
    this.modal.destroy();
  }
}
